const {createConnection, Socket} = require('net');
const {connect, TLSSocket} = require('tls');
const Protocol = require('./Protocol');

/**
 * @author ycx
 * @description 连接核心
 */
class NetCore {


    /**
     * 构造
     * @param params {Object}
     */
    constructor(params) {

        this.host = params.host;
        this.port = params.port;
        this.password = params.password;
        this.timeout = params.timeout;

        if (params.tls &&
            params.tls.key instanceof Buffer && params.tls.cret instanceof Buffer) {
            this.tls.key = params.tls.key;
            this.tls.key = params.tls.cret;
            this.socket = connect({
                host: this.host || '127.0.0.1',
                port: this.port || 6379,
                key: this.tls.key,
                cret: this.tls.cret
            })
        } else {
            this.socket = createConnection({
                host: this.host || '127.0.0.1',
                port: this.port || 6379,
            })
        }
        this.protocol = new Protocol();
        this.callbacks = [];
        this.init();


    }

    /**
     *
     */
    init() {
        this.socket.on("connect", () => {
            if ("function" === typeof this.handle_connect) {
                console.log("链接成功")
            }
        });
        this.socket.on("timeout", () => {
            console.log("链接超时")
        });
        this.socket.on("error", err => {
            console.log("链接异常", err)
        });
        this.socket.on("close", (had_error) => {
            console.log("链接关闭", had_error)
        });
        this.socket.on("data", data => {
            console.log(data.toString('utf-8'))
            console.log("数据接收");
        });
    }


    close() {
        this.socket.end();
    }

    auth() {
    }

    command(...params) {
        return new Promise((resolve, reject) => {
            this.callbacks.push((err, res) => {
                err ? reject(res) : resolve(res);
            });
            this.socket.write(this.protocol.encode(...params));
        });
    }


}

module.exports = NetCore

/*const netCore = new NetCore({
    host: '175.24.115.200',
    port: 6379
});

netCore.command('AUTH', '1234567').then(res => {
    console.log(res)
})
netCore.command('KEYS', '*').then(res => {
    console.log(res)
})*/

